package com.example.zbh.dsliao.ui.activty;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;


import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VideoMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.media.IGxStatusCallback;
import com.easemob.util.FileUtils;
import com.easemob.util.PathUtil;
import com.example.zbh.dsliao.R;

import com.example.zbh.dsliao.application.App;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.ImageViewpager;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.ui.adapter.ChatAdapter;
import com.example.zbh.dsliao.ui.adapter.FaceAdapter;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.view.CusLargeDialog;
import com.example.zbh.dsliao.view.CustomChangeDialog;
import com.hp.hpl.sparta.xpath.PositionEqualsExpr;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import de.greenrobot.dao.internal.FastCursor;
import de.greenrobot.event.EventBus;


/**
 * 聊天页面activity
 */
public class CharActivity extends BaseActivity implements View.OnClickListener, EMEventListener, FaceAdapter.OnRecyclerItemClickListener, ChatAdapter.OnItemChatOneLongClickListener, View.OnTouchListener, ChatAdapter.OnVoiceClickListener, ChatAdapter.OnShowVideoClickListener, ChatAdapter.OnFileClickListener, ChatAdapter.OnImageClickListener {
    private InputMethodManager inputMethodManager;
    private ListView listView;
    private LinearLayout back, chatLin, lin_backG;
    private boolean isChatLin = true;//控制chatlin的显示
    private EditText input_text;
    private Button send;
    private ImageView voice, face, plus;//按住说话, 表情, 加号
    private Button speak, add_contact;//按住说话按钮, 删除聊天记录按钮
    private String username, Msg_Id_T;
    private TextView add_list_friends;//顶部用户名
    private TextView picture_tv, camera_tv, location_tv, voice_tv, video_tv, file_tv, video_phone_tv;//传相片,拍照,位置
    private File cameraFile;//相册文件
    private EMConversation conversation;
    private List<EMMessage> list = new ArrayList<>();
    private MediaRecorder mediaRecorder;//录音
    private ChatAdapter listViewAdapter;
    private List<Constant> msgs = new ArrayList<Constant>();
    private MediaPlayer player;
    private EMMessage message;
    private CustomChangeDialog customChangeDialog;
    private CustomChangeDialog customChangeDialogtext;
    private PreferenceHelper preferenceHelper;

    private Handler handler;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refrech();
        }
    };
    private RecyclerView recyclerView;
    private GridLayoutManager manager;
    private FaceAdapter faceAdapter;
    private boolean isFace = true;
    private String backGroundType;

    private String MsgId;
    private CusLargeDialog cusLargeDialog;

    //语音文件夹
    private File diaoFile;
    private UserContact userContact;

    private RequestQueue queue;


    @Override
    protected int getLayOut() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {
        back = (LinearLayout) findViewById(R.id.back);
        add_list_friends = (TextView) findViewById(R.id.add_list_friends);
        chatLin = (LinearLayout) findViewById(R.id.chatLin);
        picture_tv = (TextView) findViewById(R.id.picture_tv);
        camera_tv = (TextView) findViewById(R.id.camera_tv);
        input_text = (EditText) findViewById(R.id.input_text);
        send = (Button) findViewById(R.id.send);
        listView = (ListView) findViewById(R.id.listView);
        plus = (ImageView) findViewById(R.id.plus);
        input_text.addTextChangedListener(watcher);//编辑框监听事件
        voice = (ImageView) findViewById(R.id.voice);
        face = (ImageView) findViewById(R.id.face);
        speak = (Button) findViewById(R.id.speak);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        location_tv = (TextView) findViewById(R.id.location_tv);
        add_contact = findeView(R.id.add_contact);
        voice_tv = findeView(R.id.voice_tv);
        video_tv = findeView(R.id.video_tv);
        file_tv = findeView(R.id.file_tv);
        video_phone_tv = findeView(R.id.video_phone_tv);
        lin_backG = findeView(R.id.lin_backG);
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        backGroundType = PreferenceHelper.getInstance().getCurrentuserBackground(EMChatManager.getInstance().getCurrentUser());
        setBackGround();
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Intent intent = getIntent();
        username = intent.getStringExtra("userName");
        UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleByName(username);

        if (userContact != null) {
            String nickName = userContact.getNickname();
            if (nickName != null) {//如果传过来的是昵称
                add_list_friends.setText(nickName);
                username = userContact.getUsername();
                Log.i("yaolin", username);
            }
        } else {
            add_list_friends.setText(username);
        }
        Msg_Id_T = intent.getStringExtra("Msg_Id_T");//获取传过来的一条消息的id
        preferenceHelper = PreferenceHelper.getInstance();//初始化缓存
        listViewAdapter = new ChatAdapter(this);
        listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemChatOneLongClickListener(this);
        listViewAdapter.setOnVoiceClickListener(this);
        listViewAdapter.setOnShowVideoClickListener(this);
        listViewAdapter.setOnFileClickListener(this);
        listViewAdapter.setOnImageClickListener(this);
        back.setOnClickListener(this);
        picture_tv.setOnClickListener(this);
        camera_tv.setOnClickListener(this);
        send.setOnClickListener(this);
        plus.setOnClickListener(this);
        input_text.setOnTouchListener(this);
        voice.setOnClickListener(this);
        face.setOnClickListener(this);
        speak.setOnTouchListener(this);
        video_phone_tv.setOnClickListener(this);
        manager = new GridLayoutManager(this, 3, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        faceAdapter = new FaceAdapter();
        faceAdapter.addData(Constant.faces);
        recyclerView.setAdapter(faceAdapter);
        faceAdapter.setOnRecyclerItemClickListener(this);
        location_tv.setOnClickListener(this);
        add_contact.setOnClickListener(this);
        voice_tv.setOnClickListener(this);
        video_tv.setOnClickListener(this);
        file_tv.setOnClickListener(this);

        refrech();
        handler = new Handler();
        sendTransmitMessage();//获取被动转发过来的消息 直接发送出去
        //新消息监听
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck});
    }

    /**
     * 监听主界面的eventbus发过来的的状态
     * (包括 1 == 账号被服务器删除
     * 2 == 账号被别的设备登录)
     **/
    public void onEventMainThread(Integer data) {
        if (data == 2) {
            DliaoUtils.showDialogConnection(this);
        } else if (data == 1) {
            DliaoUtils.showDialogUserRemoved(this);
        }
    }

    //设置聊天的背景
    private void setBackGround() {
        if (backGroundType != null) {
            switch (backGroundType) {
                case Constant.GIRL_ONE:
                    setBackGroundResource(Constant.GIRL_ONE_ID);
                    break;
                case Constant.GIRL_TWO:
                    setBackGroundResource(Constant.GIRL_TWO_ID);
                    break;
                case Constant.GIRL_THREE:
                    setBackGroundResource(Constant.GIRL_THREE_ID);
                    break;
                case Constant.JOURNEY_ONE:
                    setBackGroundResource(Constant.JOURNEY_ONE_ID);
                    break;
                case Constant.JOURNEY_TWO:
                    setBackGroundResource(Constant.JOURNEY_TWO_ID);
                    break;
                case Constant.JOURNET_THREE:
                    setBackGroundResource(Constant.JOURNET_THREE_ID);
                    break;
                case Constant.FRIEND:
                    setBackGroundResource(Constant.FRIEND_ID);
                    break;
                case Constant.BOY_ONE:
                    setBackGroundResource(Constant.BOY_ONE_ID);
                    break;
                case Constant.BOY_TWO:
                    setBackGroundResource(Constant.BOY_TWO_ID);
                    break;
            }
        }

    }

    //设置聊天背景的id
    private void setBackGroundResource(int id) {
        lin_backG.setBackgroundResource(id);
    }

    /**
     * 获取被转发过来的消息
     * 并直接发送出去
     **/
    private void sendTransmitMessage() {
        if (Msg_Id_T != null && Msg_Id_T.length() > 0) {
            final EMMessage msg = EMChatManager.getInstance().getMessage(Msg_Id_T);
            EMMessage.Type type = msg.getType();
            switch (type) {
                case TXT://转发文字
                    String content = ((TextMessageBody) msg.getBody()).getMessage();
                    sendTextMessage(content);
                    break;
                case IMAGE: //转发图片
                    String filePath = ((ImageMessageBody) msg.getBody()).getLocalUrl();
                    sendImageMessage(filePath);
                    break;
                case FILE://转发文件
                    FileMessageBody fileMessageBody = (FileMessageBody) msg.getBody();
                    String url = fileMessageBody.getLocalUrl();
                    sendFileMessage(url);
                    break;
                case VIDEO://转发视频
                    VideoMessageBody videoMessageBody = (VideoMessageBody) msg.getBody();
                    String videourl = videoMessageBody.getLocalUrl();
                    String thumbPath = videoMessageBody.getThumbnailUrl();
                    int videoLength = videoMessageBody.getLength();
                    sendVideoMessage(videourl, thumbPath, videoLength);
                    break;
            }
        }
    }


    /***
     * 编辑框edittext监听
     **/
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                plus.setVisibility(View.VISIBLE);
                send.setVisibility(View.GONE);
            } else {
                plus.setVisibility(View.GONE);
                send.setVisibility(View.VISIBLE);
            }
        }
    };


    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        switch (emNotifierEvent.getEvent()) {
            case EventNewMessage:
                Log.i("nanna", ">>>>>>>>>>>>");
                handler.postDelayed(runnable, 200);
                break;
        }
    }

    //表情监听
    @Override
    public void OnRecyclerItemClick(int position) {
        Html.ImageGetter imageGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);
                Drawable drawable = getResources().getDrawable(id);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                return drawable;
            }
        };
        CharSequence cs = Html.fromHtml("<img src='" + Constant.faces[position] + "'/>", imageGetter, null);
        input_text.getText().append(cs);
    }

    //转化表情
    public String FilterHtml(String str) {
        str = str.replaceAll("<(?!br|img)[^>]+>", "").trim();
        return str;
    }

    private boolean isVoice = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.voice://按住说话按钮
                clickVoice();
                break;
            case R.id.send://发送一条文字消息
                sendTextMessage();
                break;
            case R.id.plus://加号
                clickPlus();
                break;
            case R.id.picture_tv:
                selectPicFromLocal();
                break;
            case R.id.camera_tv:
                selectPicFromCamera();
                break;
            case R.id.face://笑脸
                clickFace();
                hideSoftKeyboard();
                break;
            case R.id.location_tv://位置
                clicklocation_tv();
                break;
            case R.id.add_contact://删除聊天记录
                clickDelete();
                break;
            case R.id.voice_tv://发送语音
                clickVoiceTv();
                break;
            case R.id.video_tv://发送视频
                clickVideoTv();
                break;
            case R.id.file_tv:
                selectFileFromLocal();
                break;
            case R.id.video_phone_tv:
                clickVideoPhoneTv();
                break;
        }
    }


    /**
     * 删除聊天记录按钮
     **/
    private void clickDelete() {
        final CustomChangeDialog customChangeDialog = new CustomChangeDialog(this, "您确定要删除聊天记录么?", View.GONE, "", "删除!", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        customChangeDialog.dismiss();
                        //删除对应联系人的聊天记录
                        EMChatManager.getInstance().clearConversation(username);
                        refrech();
                        break;
                    case R.id.cancleBtn:
                        customChangeDialog.dismiss();
                        break;
                }
            }
        });

    }


    //点击语音
    private void clickVoiceTv() {
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(this, "尚未连接服务器,请稍后再试", Toast.LENGTH_SHORT).show();
            ;
        } else {
            Intent intent = new Intent();
            intent.setClass(this, VoiceCallActivity.class);
            intent.putExtra("username", username);
            intent.putExtra("isComingCall", false);
            startActivity(intent);

        }

    }

    //点击视频通话
    private void clickVideoPhoneTv() {
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(this, "尚未连接服务器,请稍后再试", Toast.LENGTH_SHORT).show();
        } else {
            Intent intent = new Intent();
            intent.setClass(this, VideoCallActivity.class);
            intent.putExtra("username", username);
            intent.putExtra("isComingCall", false);
            startActivity(intent);
        }
    }

    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 1);
    }

    //点击视频
    private void clickVideoTv() {
        Intent intent = new Intent();
        intent.setClass(this, SendVideoActivity.class);
        startActivityForResult(intent, 4);
    }


    /**
     * 位置按钮
     **/
    private void clicklocation_tv() {
        Intent intent = new Intent(this, LocationActivity.class);
        startActivityForResult(intent, 250);
    }


    /**
     * 按住说话按钮
     **/
    private void clickVoice() {
        hideSoftKeyboard();
        recyclerView.setVisibility(View.GONE);
        chatLin.setVisibility(View.GONE);
        face.setImageResource(R.drawable.face);
        if (isVoice) {
            voice.setImageResource(R.drawable.keyboard);
            input_text.setVisibility(View.GONE);
            speak.setVisibility(View.VISIBLE);
            isFace = true;
            isChatLin = true;
        } else {
            voice.setImageResource(R.drawable.voice);
            speak.setVisibility(View.GONE);
            input_text.setVisibility(View.VISIBLE);
            isFace = true;
            isChatLin = true;
        }
        isVoice = !isVoice;
    }


    /**
     * 笑脸按钮
     **/
    private void clickFace() {
        hideSoftKeyboard();
        chatLin.setVisibility(View.GONE);
        voice.setImageResource(R.drawable.voice);
        speak.setVisibility(View.GONE);
        input_text.setVisibility(View.VISIBLE);
        if (isFace) {
            face.setImageResource(R.drawable.faced);
            recyclerView.setVisibility(View.VISIBLE);
            isVoice = true;
            isChatLin = true;
        } else {
            face.setImageResource(R.drawable.face);
            recyclerView.setVisibility(View.GONE);
            isVoice = true;
            isChatLin = true;
        }
        isFace = !isFace;
    }


    /**
     * 加号按钮
     **/
    private void clickPlus() {
        hideSoftKeyboard();
        face.setImageResource(R.drawable.face);
        if (isChatLin) {
            recyclerView.setVisibility(View.GONE);
            chatLin.setVisibility(View.VISIBLE);
            isVoice = true;
            isFace = true;
        } else {
            chatLin.setVisibility(View.GONE);
            isVoice = true;
            isFace = true;
        }
        isChatLin = !isChatLin;

    }

    /**
     * 发送一条文字消息
     **/
    private void sendTextMessage() {
        String content = FilterHtml(Html.toHtml(input_text.getText()));

        if (!"".equals(content)) {
            //获取到与聊天人得会话对象.参数username为聊天人的userid活着groupid
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            //创建一条文本消息
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            //如果是群聊设置chattype,默认的是单聊
//                    message.setChatType(EMMessage.ChatType.Chat);
            //设置消息body
            TextMessageBody textMessageBody = new TextMessageBody(content);
            message.addBody(textMessageBody);
            //设置接收人
            message.setReceipt(username);
            //把消息加入到此会话对象中
            conversation.addMessage(message);

            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.i("chart", "发送成功");
                }

                @Override
                public void onError(int i, String s) {
                    Log.i("chart", "发送失败");
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
            input_text.setText("");//清空输入框内容
        }
        handler.postDelayed(runnable, 200);
    }

    //语音录制
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.input_text:
                chatLin.setVisibility(View.GONE);
                face.setImageResource(R.drawable.face);
                recyclerView.setVisibility(View.GONE);
                Log.i("sdadasdsadas", ">>>>>>>>");
                break;
            case R.id.speak:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startRecording();
                        break;
                    case MotionEvent.ACTION_UP:
                        stopRecording();
                        break;
                }
                break;
        }
        return false;
    }

    //语音播放
    @Override
    public void OnVoiceClick(String name) {
        startPlaying(name);
    }

    //播放视频
    @Override
    public void onShowVideoClick(EMMessage message) {
        VideoMessageBody videoMessageBody = (VideoMessageBody) message.getBody();
        Intent intent = new Intent();
        intent.setClass(this, ShowVideoActivity.class);
        intent.putExtra("localpath", videoMessageBody.getLocalUrl());
        intent.putExtra("secret", videoMessageBody.getSecret());
        intent.putExtra("remotepath", videoMessageBody.getRemoteUrl());
        startActivity(intent);
    }

    //打开文件
    @Override
    public void onFileClick(EMMessage message) {
        NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
        String filePath = fileMessageBody.getLocalUrl();
        File file = new File(filePath);
        if (file != null && file.exists()) {
            FileUtils.openFile(file, this);
        } else {
            Intent intent = new Intent();
            intent.putExtra("msgbody", message.getBody());
            intent.setClass(this, ShowNomalFileActivity.class);
            startActivity(intent);
        }
        if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked) {
            try {
                EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                message.isAcked = true;
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }
    }

    //开始播放语音
    private void startPlaying(String name) {
        try {
            player = new MediaPlayer();
            player.setDataSource(name);
            player.prepare();
            player.start();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlaying();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //停止语音
    private void stopPlaying() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    //开始录音
    public void startRecording() {
        try {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置麦克风
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);//设置输出文件
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//设置编码格式
            if (DliaoUtils.isExitsSdcard()) {
                String fileName = System.currentTimeMillis() + ".mp3";
                diaoFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/diao");
                if (!diaoFile.exists()) {
                    diaoFile.mkdir();
                }
                diaoFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/diao/" + fileName);
                if (!diaoFile.exists()) {
                    diaoFile.createNewFile();
                }
                Log.i("sssddddd", diaoFile.getAbsolutePath() + "   " + fileName);
                mediaRecorder.setOutputFile(diaoFile.getAbsolutePath());
                mediaRecorder.prepare();
                mediaRecorder.start();

                Log.i(" mediaRecorder.start();", "开始录音");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //结束录音
    public void stopRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setOnInfoListener(null);
            mediaRecorder.stop();
            Log.i("sssssddd", " mediaRecorder.stop();");
            mediaRecorder.release();
            mediaRecorder = null;
            sendVoiceMessage(diaoFile.getAbsolutePath(), (int) diaoFile.getAbsoluteFile().length());
        }
    }


    /**
     * 长按一条消息 删除或复制
     **/
    @Override
    public void OnChatOneLongClick(View view, String MsgId, int type) {
        Log.d("fucktype", "type:" + type);
        if (type == 0) {//txt类型弹出框
            showDialogCopy(MsgId);
        } else if (type == 1) {//其他消息
            showDialog(MsgId);
        } else if (type == 2) {//语音消息
            showDialogS(MsgId);
        }
    }

    /**
     * 除了txt和image类型
     * 弹出的dialog
     **/
    private void showDialogS(final String MsgId) {
        customChangeDialog = new CustomChangeDialog(this, "请选择", View.GONE, "", "删除本条消息", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn://删除
                        customChangeDialog.dismiss();
                        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
                        conversation.removeMessage(MsgId);
                        refrech();
                        break;
                    case R.id.cancleBtn://取消
                        customChangeDialog.dismiss();
                        break;
                }
            }
        });
    }

    /**
     * 如果这一条消息不是txt类型的
     * 弹出的dialog
     **/
    private void showDialog(final String MsgId) {
        customChangeDialog = new CustomChangeDialog(this, "请选择..", View.VISIBLE, "删除本条消息", "转发本条消息", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeOneBtn://删除
                        customChangeDialog.dismiss();
                        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
                        conversation.removeMessage(MsgId);
                        refrech();
                        break;
                    case R.id.changeTwoBtn://转发一条消息
                        Intent intent = new Intent(CharActivity.this, TransmitActivity.class);
                        intent.putExtra("Msg_Id", MsgId);
                        startActivity(intent);
                        finish();
                        customChangeDialog.dismiss();
                        break;
                    case R.id.cancleBtn:
                        customChangeDialog.dismiss();
                        break;
                }
            }
        });
    }

    /**
     * 长按一条消息弹出dialog
     * (txt类型的消息)
     **/
    private void showDialogCopy(final String MsgId) {
        customChangeDialogtext = new CustomChangeDialog(this, "请选择..", View.VISIBLE, "删除本条消息", "转发本条消息", "复制本条消息");
        customChangeDialogtext.show();
        customChangeDialogtext.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeOneBtn://删除
                        customChangeDialogtext.dismiss();
                        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
                        conversation.removeMessage(MsgId);
                        refrech();
                        break;
                    case R.id.changeTwoBtn://转发一条消息
                        Intent intent = new Intent(CharActivity.this, TransmitActivity.class);
                        intent.putExtra("Msg_Id", MsgId);
                        startActivity(intent);
                        finish();
                        customChangeDialogtext.dismiss();
                        break;
                    case R.id.cancleBtn://复制这一条消息
                        customChangeDialogtext.dismiss();
                        //根据传过来的msgid查询这一整条的内容
                        EMMessage emMessage = EMChatManager.getInstance().getMessage(MsgId);
                        TextMessageBody body = (TextMessageBody) emMessage.getBody();
                        //获得内容
                        String thismessage = body.getMessage();
                        //构建系统粘贴板对象 并将字符串存进去
                        ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        cmb.setText(thismessage);

                        Toast.makeText(CharActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }


    /**
     * 点击图片类型消息
     **/
    @Override
    public void onImageClick(String user, EMMessage message) {
        //根据用户名查询全部与这个人聊天中的图片url
        List<ImageViewpager> viewpagers = DatabaseHelper.getInstance().queryimageViewpagerAll(username);
        ImageMessageBody messageBody = (ImageMessageBody) message.getBody();
        String url = null;
        int index = 0;
        switch (message.direct){
            case SEND:
                url = messageBody.getLocalUrl();
                for (int i = 0; i < viewpagers.size(); i++) {
                    if (viewpagers.get(i).getImageUrl().equals(url)){
                        index = i;
                    }
                }
                break;
            case RECEIVE:
                 url = messageBody.getThumbnailUrl();
                for (int i = 0; i < viewpagers.size(); i++) {
                    if (viewpagers.get(i).getImageUrl().equals(url)){
                        index = i;
                    }
                }
                break;
        }
//        Log.d("gedadada", "viewpagers:" + viewpagers + viewpagers.get(2));
        cusLargeDialog = new CusLargeDialog(this, viewpagers, index);
        cusLargeDialog.show();
    }

    //隐藏键盘
    public void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private boolean isSaveImage = true;
    /**
     * 刷新
     **/
    public void refrech() {
        conversation = EMChatManager.getInstance().getConversation(username);
        conversation.markAllMessagesAsRead();
        list = conversation.getAllMessages();
        Log.d("CharActivity", "conversation:" + conversation.getAllMessages());
        Log.i("Sysout", "size" + list.size() + "---");
        String nowname = EMChatManager.getInstance().getCurrentUser();
        listViewAdapter.addData(list, username);
        //将listview定位到最后一行
        listView.setSelection(list.size());
        DatabaseHelper.getInstance().deleteImageViewPager();

        for (EMMessage emMessage : list) {
            if (emMessage.getType() == EMMessage.Type.IMAGE) {
                ImageMessageBody messageBody = (ImageMessageBody) emMessage.getBody();
                String url = messageBody.getLocalUrl();
                switch (emMessage.direct){
                    case RECEIVE:
                        if (url != null && url.length() > 0){
                            String urlth = messageBody.getThumbnailUrl();
                            //把当前图片url和username设置给一个对象 并添加到数据库中
                            ImageViewpager imageViewpager = new ImageViewpager();
                            imageViewpager.setUsername(username);
                            imageViewpager.setImageUrl(urlth);
                            DatabaseHelper.getInstance().saveImageUrl(imageViewpager);
                            Log.d("gedadadada", "imageViewpager:" + imageViewpager.getImageUrl() + "<><><><><><><>><" + imageViewpager.getUsername());
                        }
                        break;
                    case SEND:
                        if (url != null && url.length() > 0){
                            //把当前图片url和username设置给一个对象 并添加到数据库中
                            ImageViewpager imageViewpager = new ImageViewpager();
                            imageViewpager.setUsername(username);
                            imageViewpager.setImageUrl(url);
                            DatabaseHelper.getInstance().saveImageUrl(imageViewpager);
                            Log.d("gedadadada", "imageViewpager:" + imageViewpager.getImageUrl() + "<><><><><><><>><" + imageViewpager.getUsername());
                        }
                        break;
                }

            }
        }
//        Log.d("CharActivity", "DatabaseHelper.getInstance().queryimageViewpagerAll(username).size():" + DatabaseHelper.getInstance().queryimageViewpagerAll(username).size() + "~~~~~~~~~~~~");

    }

    //拍照功能
    private void selectPicFromCamera() {
        if (!DliaoUtils.isExitsSdcard()) {
            Toast.makeText(this, "sd卡不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMChatManager.getInstance().getCurrentUser() + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                2);
    }

    //从图库选取照片
    public void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 3);//本地相册请求码
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 3) {
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                        handler.postDelayed(runnable, 200);
                    }
                }
            } else if (requestCode == 2) {
                if (cameraFile != null && cameraFile.exists()) {
                    sendImageByCamera(cameraFile.getAbsolutePath());
                    handler.postDelayed(runnable, 200);
                }

            } else if (requestCode == 4) {
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    Log.i("hjjkkllljjhh", videoPath);
                    File file = new File(PathUtil.getInstance().getImagePath(), "dlvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                        fileOutputStream.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);


                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            } else if (requestCode == 1) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }


            } else if (requestCode == 250 && resultCode == 360) {//返回的位置信息
                String addr = data.getStringExtra("location");
                double latitude = Double.parseDouble(data.getStringExtra("latitude"));
                double longitude = Double.parseDouble(data.getStringExtra("longitude"));

                if (addr != null && !addr.equals("")) {
                    //发送一条文字消息(当前位置)
                    sendLocationMessage(latitude, longitude, addr);

                } else {
                    Toast.makeText(this, "木有发现你的位置..请重新定位", Toast.LENGTH_SHORT).show();
                }

            }

        }
    }

    private void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = this.getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        //大于10M不让发送
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(this, "文件不能大于10", Toast.LENGTH_SHORT).show();
            return;
        }
        sendFileMessage(filePath);
    }


    //根据图库图片的uri发送图片
    private void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (picturePath == null || picturePath.equals("null")) {
                Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            //大于10M不让发送
            if (file.length() > 10 * 1024 * 1024) {
                Toast.makeText(this, "文件不能大于10M", Toast.LENGTH_SHORT).show();
                return;
            }
            sendImageMessage(file.getAbsolutePath());
        }
    }


    //发送消息的方法///////////////////////////////////////////////////////////////////////
    private void sendImageMessage(String picturePath) {
        EMMessage message = EMMessage.createImageSendMessage(picturePath, false, username);
        sendMessage(message);
    }

    private void sendVideoMessage(String videoPath, String absolutePath, int duration) {
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, absolutePath, duration, username);
        sendMessage(message);
    }

    //发送文件
    private void sendFileMessage(String filePath) {
        EMMessage message = EMMessage.createFileSendMessage(filePath, username);
        sendMessage(message);
    }

    private void sendImageByCamera(String absolutePath) {
        EMMessage message = EMMessage.createImageSendMessage(absolutePath, false, username);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, username);
        sendMessage(message);
    }

    private void sendMessage(EMMessage message) {
        EMChatManager.getInstance().sendMessage(message, null);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, username);
        sendMessage(message);
    }

    protected void sendTextMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, username);
        sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        EMChatManager.getInstance().unregisterEventListener(this);
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }


    }


}
